package com.sfx.concurrent.demo.concurrent.ReentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-09
 * Time: 16:55
 */

@Slf4j(topic = "c.TryLock")
public class TryLock {
    /**
     * 演示ReentrantLock锁超时的情况
     */
    private static ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            try {
                if(!lock.tryLock(1, TimeUnit.SECONDS)) {
                    log.debug("没有获取到锁,立即返回");
                    return;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                //tryLock也可以被打断,没有获取到锁
                log.debug("被打断,没有获取到锁,立即返回");
                return;
            }
            log.debug("获取到锁");
            try {
                //执行临界区代码
                log.debug("执行临界区代码");
            }finally {
                //解锁
                lock.unlock();
            }
        },"t1");
        log.debug("获取锁");
        lock.lock();
        t1.start();
        try{
            Thread.sleep(2000);
        }finally {
            log.debug("释放锁");
            lock.unlock();
        }
    }
}